package com.example.bluetooth;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    public static final String  DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    public static String EXTRA_DEVICE_ADDRESS="device_address";
    private BluetoothAdapter mBluetoothAdapter = null;
    private ChatService mChatService = null;
    private String MainTag = "mainTag";
    private Button btn_send,btn_link,btn_find;
    private TextView tv_show_send_data,tv_show_read_data,mTitle;
    private EditText text;
    private String mConnectedDeviceName = null;
    public static final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_send = findViewById(R.id.btn_send);
        btn_link = findViewById(R.id.btn_link);
        btn_find = findViewById(R.id.btn_find);
        tv_show_send_data = findViewById(R.id.tv_show_send_data);
        tv_show_read_data = findViewById(R.id.tv_show_read_data);
        text = findViewById(R.id.et_data);
        mTitle = findViewById(R.id.tv_show_status);

        btn_link.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, BluetoothShowActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.e(MainTag, "-- btn_send -- ");
                sendMessage(text.getText().toString());
            }
        });

        btn_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 让自身可以被发现
                if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //设置本机蓝牙在 300 秒之内可以被 搜索
                    startActivity(discoverableIntent);
                }
            }
        });
        // 得到本地蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //若当前设备不支持蓝牙功能
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        direction();
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e(MainTag, "-- onStart -- ");
        if ( mChatService == null ){
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            }
            setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        Log.e(MainTag, "-- onResume -- ");
        if (mChatService != null) {
            Log.e(MainTag, "-- onResume :  " + mChatService.getState());
            if (mChatService.getState() == ChatService.STATE_NONE) {
                Log.e(MainTag, "-- onResume : ChatService ");
                mTitle.setText("等待连接...");
                // 开启监听
                mChatService.start();
            }
        }
    }

    private void setupChat() {
        Log.e(MainTag, "-- setupChat -- ");
        mChatService = new ChatService(this, mHandler);
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        Log.e(MainTag, "-- onPause -- ");
    }
    @Override
    public void onStop() {
        super.onStop();
        Log.e(MainTag, "-- onStop -- ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(MainTag, "-- onDestroy -- ");
        if (mChatService != null)
            mChatService.stop();
    }

    private void sendMessage(String message) {
        if (mChatService.getState() != ChatService.STATE_CONNECTED) {
            Toast.makeText(this, "Main：还没连上", Toast.LENGTH_SHORT).show();
            return;
        }
        if (message.length() > 0) {
            Log.e(MainTag, "-- sendMessage -- ok");
            byte[] send = message.getBytes();
            mChatService.write(send);
        }
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.e(MainTag, "-- Handler -- ");
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case ChatService.STATE_CONNECTED:
                            mTitle.setText("已经连接到：");
                            mTitle.append(mConnectedDeviceName);
                            break;
                        case ChatService.STATE_CONNECTING:
                            mTitle.setText("准备连接到...");
                            break;
                        case ChatService.STATE_LISTEN:
                        case ChatService.STATE_NONE:
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    String writeMessage = new String(writeBuf);
                    tv_show_send_data.setText("我：" + writeMessage);
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    tv_show_read_data.setText("Ta：" + readMessage);
                    break;
                case MESSAGE_DEVICE_NAME:
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    Toast.makeText(getApplicationContext(), "链接到" + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                    mTitle.setText(msg.getData().getString(TOAST));
                    break;
            }
        }
    };

    public void direction(){
        findViewById(R.id.btn_up).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONA");
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONF");
                }
                view.performClick();
                return false;
            }
        });

        findViewById(R.id.btn_down).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONB");
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONF");
                }
                view.performClick();
                return false;
            }
        });

        findViewById(R.id.btn_left).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONC");
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONF");
                }
                return false;
            }
        });

        findViewById(R.id.btn_right).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("OND");
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONF");
                }
                return false;
            }
        });

        findViewById(R.id.btn_stop).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONF");
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP && mChatService.getState() == ChatService.STATE_CONNECTED ) {
                    sendMessage("ONF");
                }
                return false;
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e(MainTag, "-- onActivityResult -- ");
        if (requestCode == 100) {
            if (resultCode == Activity.RESULT_OK) {
                Log.e(MainTag, "-- onActivityResult -- ing ");
                String address = data.getStringExtra(EXTRA_DEVICE_ADDRESS);
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                Log.e(MainTag, " 设备名字：" +device.getName() + "   设备地址：" + address);
                mChatService.connect(device);
            }
        }
    }
}
